package com.campus.shop.controller.web;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.shop.common.Result;
import com.campus.shop.controller.web.vo.UserVo;
import com.campus.shop.entity.User;
import com.campus.shop.exception.ServiceException;
import com.campus.shop.mapper.UserMapper;
import com.campus.shop.service.UserService;
import com.campus.shop.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.HashMap;

/**
 * @author xr
 * @since 2023-12-25 16:32:04
 */
@RestController
@RequestMapping("/web/user/")
public class UserController extends BaseWebController {
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     * @param userInput
     * @param password
     * @return
     */
    @PostMapping("user-login")
    public Result userLogin(@RequestParam("userInput") String userInput, @RequestParam("password") String password){
        User user = userService.userLogin(userInput,password);
        String token = TokenUtils.createToken(String.valueOf(user.getId()),user.getTelephone());
        HashMap<String, Object> res = new HashMap<>();
        UserVo userVo = new UserVo();
        userVo.setUserName(user.getUserName());
        userVo.setAvatar(user.getAvatar());
        userVo.setAccountMoney(user.getAccountMoney());
        res.put("userToken",token);
        res.put("userInfo",userVo);
        return Result.success(res);
    }

    /**
     * 注册
     * @param telephone
     * @param password
     * @return
     */
    @PostMapping("user-register")
    public Result userRegister(@RequestParam("telephone") String telephone, @RequestParam("password") String password ){
        Boolean result = userService.userRegister(telephone,password);
        return result ? Result.success() : Result.error();
    }

    /**
     * 更新信息
     * @param userVo
     * @return
     */
    @PostMapping("set-user-info")
    public Result setUserInfo(@RequestBody UserVo userVo){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",getUserId());
        User user = userMapper.selectOne(wrapper);
        user.setUserName(userVo.getUserName());
        user.setAvatar(userVo.getAvatar());
        user.setSex(userVo.getSex());
        userMapper.update(user,wrapper);
        return Result.success();
    }

    /**
     * 获取学生信息
     * @return
     */
    @PostMapping("get-user-info")
    public Result getUserInfo(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",getUserId());
        wrapper.select("user_name,avatar,sex,account_money");
        User user = userMapper.selectOne(wrapper);
        return Result.success(user);
    }



}


